package cn.zhouixi.ws.listener;
import cn.zhouixi.ws.pojo.User;
import cn.zhouixi.ws.utils.RedisUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@WebListener
public class SubscribeListener implements MessageListener , ServletContextListener {

    private static RedisUtils redisUtils;
    // 维护关系表 代替db
    private static Map<String,Long> map = new ConcurrentHashMap<>();

    private Session session;

    private Long userId ;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        redisUtils = WebApplicationContextUtils
                .getWebApplicationContext(sce.getServletContext())
                .getBean(RedisUtils.class);
    }

    public void setSession(Session session, Long userId) {
        this.session = session;
        this.userId = userId;
    }

    /**
     * 接收发布者的消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String msg = new String(message.getBody());
        if(session == null) {
            return;
        }
        String newMsg = msg.substring(1, msg.length() - 1).replaceAll("\\\\","");;
                //
        //StringEscapeUtils.unescapeJava(str);
        User user = JSON.parseObject(newMsg,  User.class);

        if (session.isOpen() && user.getUserId().equals(userId)) {
            try {
                System.out.println(new String(pattern) + "主题发布：" + msg);
                session.getAsyncRemote().sendText(msg + "主题回复 ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
